package cn.itcast.web.shiro;

import cn.itcast.domain.system.Module;
import cn.itcast.domain.system.User;
import cn.itcast.service.system.ModuleService;
import cn.itcast.service.system.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

import static com.sun.tools.doclint.Entity.and;

public class AuthRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;
    @Autowired
    private ModuleService moduleService;

    //认证信息
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //获取用户名
        String email = (String) token.getPrincipal();

        //根据用户名查询密码
        User user = userService.findByEmail(email);

        if(user ==null){
            return null;
        }
        //获取数据库密码
        String dbPwd = user.getPassword();

        SimpleAuthenticationInfo sai = new SimpleAuthenticationInfo(user, dbPwd, getName());

        return sai;
    }

    //授权信息,告诉shiro登陆用户拥有的权限（根据用户id查询权限）
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取用户对象
        User user = (User) principalCollection.getPrimaryPrincipal();

        //通过用户id查询拥有的权限
        List<Module> moduleList = moduleService.findModuleByUserId(user.getId());

        //返回
        SimpleAuthorizationInfo sai = new SimpleAuthorizationInfo();

        if(moduleList != null && moduleList.size()>0){
            for (Module module : moduleList) {
                //告诉shiro用户拥有的权限
                sai.addStringPermission(module.getName());
            }
        }
        return sai;
    }

}
